package amalgame.ventas;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.TooManyListenersException;

import amalgame.data.DataSQLiteHelper;
import amalgame.data.DatabaseManager;
import amalgame.entity.CustomAdapter;
import amalgame.entity.ListaActividad;
import amalgame.entity.db.Customer;
import amalgame.entity.db.Orders;
import amalgame.entity.db.Product;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.j256.ormlite.dao.Dao;



public class OrdersActivity extends ListaActividad{
	//Peter
	public static Orders orderEdit = null;
	
	  ListView listView;
	  List<Orders> customerOrderList ;
	  List<String> customerOrderListStr; 
	  Dao<Orders, Integer> ordersDao;
	  DataSQLiteHelper dataSQLiteHelper;
	  private ImageButton  btn_add;
	  private DatabaseManager manager;
	  private Context mContext;
	  private Dialog customDialog;
	  private Customer customer_selection;
	  private	List<Customer> list_customer;
	  private ArrayAdapter<String> adapter_customer;
	  private String[] arr_str_customer;
	  private Spinner sp_customer;
	  static Orders orderToChange;
	  
	  static int id;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.abm_customer_order);

	
		mContext = getApplicationContext();
		manager = DatabaseManager.getInstance();
		
		list_customer = manager.getAllCustomer();
		if(list_customer!=null){
			arr_str_customer = new String[list_customer.size()];
			int x=-1;
			for (Customer item : list_customer) {
				arr_str_customer[++x] = item.getName();
			}
			adapter_customer = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arr_str_customer);
			
			btn_add = (ImageButton) findViewById(R.id.abm_custmer_account_add);
			btn_add.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					customDialog = showDialog(getString(R.string.select_a_customer));
					if(customDialog!=null)
					customDialog.show();
					
				}
			});
		}	
		

		 updateCustomerList_customAdapter();
		
		
		
		
	}
	
	private void updateCustomerList_customAdapter(){
		customerOrderList = manager.getAllOrders();
		customerOrderListStr = new ArrayList<String>();

		listView = (ListView) getListView();
		if (customerOrderList!=null && customerOrderList.size()>0){
			
			CustomAdapter_product_iconrow_custom customAdapter=		new CustomAdapter_product_iconrow_custom(mContext,					customerOrderList);			
			listView.setAdapter(customAdapter);
			registerForContextMenu(listView);
		}else{
			
			customerOrderListStr.add(getResources().getString(R.string.no_item_added));
			CustomAdapter customAdapter = new CustomAdapter(mContext, customerOrderListStr);
			listView.setAdapter(customAdapter);
			unregisterForContextMenu(listView);
		}
		
		

	}
	
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		updateCustomerList_customAdapter();
	}
	
	
	
	/**
	 * @param String message
	 * @param String title
	 * @return 
	 */
	public Dialog showDialog( String title){

		int itemSelection = 0;
		int selItem = 0;	
			customDialog = new Dialog(OrdersActivity.this);
			customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);			
			customDialog.setContentView(R.layout.simpledialog_spinner);
			customDialog.setCancelable(false);		
			
			TextView tv_title =  (TextView) customDialog.findViewById(R.id.simpledialog_spinner_textview_title);
			sp_customer  = (Spinner) customDialog.findViewById(R.id.simpledialog_spinner_spinner_customer);
			Button btn_ok     = (Button) customDialog.findViewById(R.id.simpledialog_spinner_button_ok);
			Button btn_cancel     = (Button) customDialog.findViewById(R.id.simpledialog_spinner_button_cancel);
			
			tv_title.setText(title);
		

			if(list_customer.size()==0){
				Toast.makeText(OrdersActivity.this, getString(R.string.you_must_add_a_customer_before_), Toast.LENGTH_LONG).show();
				customDialog.cancel();
				return null;
			}

			try {	
				adapter_customer.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				sp_customer.setAdapter(adapter_customer);	
				sp_customer.setSelection(0);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		
			customer_selection = null;
			
			btn_ok.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if(customer_selection!=null) {
						Date date  = new java.util.Date();
						java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyMMddHHmmss");
						String date_str = sdf.format(date);
						
						
						/*
						 * 
						 * 
						 */
						
						
						Orders p = new Orders(date_str,customer_selection.getCustomerID(),1); //new order(0, customer_selection.getCustomerID(),date);
						manager.addOrders(p);
						updateCustomerList_customAdapter();
						customDialog.cancel();
					}
				}
			});
			btn_cancel.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					customDialog.cancel();
					//finish();
				}
			});
			
			
			 sp_customer.setOnItemSelectedListener(new OnItemSelectedListener() {

				@Override
				public void onItemSelected(AdapterView<?> parentView,View selectedItemView, int position, long id) {
						try {
							String str_customer = sp_customer.getSelectedItem().toString();
							
							//List<Customer> listCustomer = manager.getAllCustomer();
							
							int i = 0;
							int iditem = -1;
							for (Customer item : list_customer) {
								if (item.getName().equals(str_customer)) {
									iditem = item.getCustomerID();
									break;
								}
						
								i++;
							}
							if(iditem!=-1)
							{
								
								customer_selection = manager.getCustomerByID(iditem);
								
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					

				}

				@Override
				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub

				}

			});
			return customDialog;
	}
	
	
	

	public class CustomAdapter_product_iconrow_custom extends BaseAdapter implements Filterable {

		private static final long serialVersionUID = 1L;
		private Context mContext;
		    //private int id;
		    private List <String>items ;
		    private List<Orders> list_items;
	        
		    private LayoutInflater mInflater;
	        private int mViewId;

		    @SuppressWarnings("unchecked")
			public CustomAdapter_product_iconrow_custom(Context context, List<Orders> list_items ) 
		    {
		        //super(context, R.layout.simpleiconrow, list);
		    	//super();
		        mContext = context;
		       this.list_items = list_items;
		       
		    }

		    public View getView(final int position, View v, ViewGroup parent)
		    {
		        View mView = v ;
		        if(mView == null){
		            LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		            mView = vi.inflate(R.layout.iconrow_customerorder, null);
		        }

		        TextView tv_title = (TextView) mView.findViewById(R.id.iconrow_customorder_tv_title);		        													
		        TextView tv_desc = (TextView) mView.findViewById(R.id.iconrow_customorder_tv_desc);
		        
		        ImageButton imb_delete = (ImageButton) mView.findViewById(R.id.iconrow_customorder_imb_delete);
		        ImageButton imb_edit = (ImageButton) mView.findViewById(R.id.iconrow_customorder_imb_edit);
		        //Peter
		        ToggleButton toggleButton = (ToggleButton) mView.findViewById(R.id.iconrow_customorder_toggle_openclose);
		        
		        
		        
		        if(list_items.get(position) != null )
		        {
					Customer c = manager.getCustomerByID(list_items.get(position).getCustomer_id());
					String customerName=  c.getName();
					String str = "CUSTOMER:"+ customerName +" ORDER: " + list_items.get(position).getId(); 
		            
					String desc = " " ;
					
					tv_title.setText(str);		            
		            tv_desc.setText(desc);
		            
		            
		            tv_title.setTextColor(Color.BLACK);
		            tv_desc.setTextColor(Color.BLACK);

		            if(list_items.get(position).getState()==1){
		            	toggleButton.setChecked(true);
		            }else{
		            	toggleButton.setChecked(false);
		            }
		            
		            //toggleButton.setVisibility(View.INVISIBLE);
		            //int color = Color.argb( 200, 255, 64, 64 );	                text.setBackgroundColor( color );

		        }
		        
		        
		        toggleButton.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						try {
							// ITEM
							int id  = customerOrderList.get(position).getId();
							
							String name = ""+ customerOrderList.get(position).getId();
							   		
							//TITTLE & TEXT
							String  title = getResources().getString(R.string.close_order);
							
							Dialog dialog = new Dialog(OrdersActivity.this);
							dialog = showDialogCerrarAbrirOrden( title, customerOrderList.get(position));
							dialog.show();			
							
						} catch (Exception e) {
							e.printStackTrace();
						}
						
					}
				});
		        
		        
		        imb_delete.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						try {
							// ITEM
							int id  = customerOrderList.get(position).getId();
							String name = ""+ customerOrderList.get(position).getId();
							   		
							//TITTLE & TEXT
							String  title = getResources().getString(R.string.customer);
							String text =  getResources().getString ( R.string.do_you_want_to_delete_this_item_) + " " + name;
							
							Dialog dialog = new Dialog(OrdersActivity.this);
							dialog = showDialogEliminar(text, title,   id);
							dialog.show();			
							
							
						
						
						} catch (Exception e) {
							e.printStackTrace();
						}
						
					}
				});
		        
		        
		        imb_edit.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						//productEdit = productList.get(position);
						int id  = customerOrderList.get(position).getId();
						
						Intent intent = new Intent();
						intent.putExtra("MODE", "EDIT");
						intent.putExtra("ORDER-ID",id );
						
						
						intent.setClass(OrdersActivity.this, OrderProductActivity.class);
						startActivity(intent);
						
						
					}
				});
		        
		        //v.setBackground(mContext.getResources().getDrawable(  R.drawable.fondolist));
		        
		        return mView;
		    }

		    
		    public int getCount() {
		        return list_items.size();
		    }

		    public Object getItem(int position) {
		        return list_items.get(position);
		    }

		    public long getItemId(int position) {
		        return position;
		    }

			@Override
			public Filter getFilter() {
				  return new Filter() {

			            @SuppressWarnings("unchecked")
			            @Override
			            protected void publishResults(CharSequence constraint,
			                    FilterResults results) {
			            	list_items = (List<Orders>) results.values;
			                CustomAdapter_product_iconrow_custom.this.notifyDataSetChanged();
			            }

			            @Override
			            protected FilterResults performFiltering(CharSequence constraint) {

			                List<Product> filteredResults = getFilteredResults(constraint);

			                FilterResults results = new FilterResults();

			                results.values = filteredResults;

			                return results;
			            }
			        };
			}

		protected List<Product> getFilteredResults(CharSequence constraint) {
			ArrayList<Product> filteredList = new ArrayList<Product>();
			for (Orders c : list_items) {
//				if (c.getCustomerOrderID()().trim().toLowerCase()
//						.startsWith(constraint.toString().trim().toLowerCase())) { 
//					filteredList.add(c);
//				}
			}
			return filteredList;
		}
			
	
	}
	
	
	
	//Peter
	public Dialog showDialogCerrarAbrirOrden( String title, final Orders orders){
		orderToChange = orders;
		
		customDialog = new Dialog(OrdersActivity.this);
		customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);			
		customDialog.setContentView(R.layout.simpledialog_okcancel);
		customDialog.setCancelable(false);		
		
		TextView tv_title =  (TextView) customDialog.findViewById(R.id.simpledialog_okcancel_title);
		TextView tv_text  = (TextView) customDialog.findViewById(R.id.simpledialog_okcancel_text);
		Button btn_ok     = (Button) customDialog.findViewById(R.id.simpledialog_okcancel_ok);
		Button btn_cancel     = (Button) customDialog.findViewById(R.id.simpledialog_okcancel_cancel);
	
		tv_title.setText(title);
		
		String message  = "";
		if( orderToChange.getState() == 1){
			message =  getResources().getString (R.string.close_order_number) + " " + orderToChange.getId();
			tv_text.setText(message);
		}else{
			message =  getResources().getString(R.string.do_you_want_yo_re_open_order_number_) + " " + orderToChange.getId();
			tv_text.setText(message);	
		}
		
		
		btn_ok.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//manager.deleteCategoryById(ID);
				//		updateCustomerList_customAdapter();
				//boolean ret = manager.updateProduct(product_selection);
				
				//Peter
				
				//List<Orders> orderList = manager.getAllOrders();
				
				try {
					
					
					if( orderToChange.getState() == 1){
						orderToChange.setState(0);//cerrada
					}else{
						orderToChange.setState(1);//abierta
					}
					
					boolean ret = manager.updateOrder(orderToChange);
					
					updateCustomerList_customAdapter();
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			
				customDialog.cancel();
				//finish();
			}
		});
		
		btn_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				/*
				if (orderToChange.getState()==1)
					toggleButton.setSelected(false);
				else
					toggleButton.setSelected(true);
				*/
				customDialog.cancel();
				//finish();
			}
		});
		return customDialog;
}	
	
	
	
	
	/**
	 * @param String message
	 * @param String title
	 * @return 
	 */
	public Dialog showDialogEliminar(String message, String title,final int id){
			//
			
			customDialog = new Dialog(OrdersActivity.this);
			customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);			
			customDialog.setContentView(R.layout.simpledialog_okcancel);
			customDialog.setCancelable(false);		
			
			TextView tv_title =  (TextView) customDialog.findViewById(R.id.simpledialog_okcancel_title);
			TextView tv_text  = (TextView) customDialog.findViewById(R.id.simpledialog_okcancel_text);
			Button btn_ok     = (Button) customDialog.findViewById(R.id.simpledialog_okcancel_ok);
			Button btn_cancel     = (Button) customDialog.findViewById(R.id.simpledialog_okcancel_cancel);
		
			tv_title.setText(title);
			tv_text.setText(message);
			
			
			btn_ok.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					//manager.deleteCategoryById(ID);
					
					//Peter
					manager.deleteOrdersById(id);

					
					updateCustomerList_customAdapter();
					customDialog.cancel();
					//finish();
				}
			});
			
			btn_cancel.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					customDialog.cancel();
					//finish();
				}
			});
			return customDialog;
	}	
	
	
}
